<template>
  <div class="user-list-page">
    <div class="page-header">
      <div class="header-content">
        <h1>用户</h1>
        <p>发现更多有趣的人</p>
      </div>
    </div>

    <div class="page-content">
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户..."
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <div class="user-grid" v-loading="loading">
        <div v-if="users.length === 0 && !loading" class="empty-state">
          <el-empty description="暂无用户" />
        </div>

        <div v-for="user in users" :key="user.id" class="user-card">
          <div class="user-avatar">
            <el-avatar :size="80" :src="user.avatar">
              {{ user.username?.charAt(0) }}
            </el-avatar>
          </div>

          <div class="user-info">
            <h3 class="username">{{ user.username }}</h3>
            <p class="bio">{{ user.profile?.bio || "这个人很懒，什么都没有留下..." }}</p>

            <div class="user-stats">
              <div class="stat-item">
                <span class="stat-value">{{ user.postCount || 0 }}</span>
                <span class="stat-label">帖子</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ user.followerCount || 0 }}</span>
                <span class="stat-label">粉丝</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ user.followingCount || 0 }}</span>
                <span class="stat-label">关注</span>
              </div>
            </div>
          </div>

          <div class="user-actions">
            <el-button
              v-if="isAuthenticated()"
              :type="user.isFollowing ? 'default' : 'primary'"
              size="small"
              @click="toggleFollow(user)"
            >
              {{ user.isFollowing ? "已关注" : "关注" }}
            </el-button>
            <el-button v-else type="primary" size="small" @click="router.push('/login')">
              登录后关注
            </el-button>
            <el-button size="small" @click="sendWhisper(user)"> 发悄悄话 </el-button>
          </div>

          <div class="join-time">加入于 {{ formatTime(user.createdAt) }}</div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[12, 24, 48]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { isAuthenticated } from "@/utils/auth";
import {
  searchUsers,
  followUser,
  unfollowUser,
  getUserStats,
  getFollowStatus,
  type UserDTO,
} from "@/api/user";

const router = useRouter();

// 扩展用户类型以包含统计信息
interface UserWithStats extends UserDTO {
  postCount?: number;
  followerCount?: number;
  followingCount?: number;
  isFollowing?: boolean;
}

// 响应式数据
const loading = ref(false);
const users = ref<UserWithStats[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(12);
const searchKeyword = ref("");

// 加载用户列表
const loadUsers = async () => {
  loading.value = true;
  try {
    let response;

    if (searchKeyword.value.trim()) {
      // 搜索用户
      response = await searchUsers({
        keyword: searchKeyword.value,
        page: currentPage.value,
        size: pageSize.value,
      });
    } else {
      // 使用搜索API获取所有用户（用空字符串搜索）
      response = await searchUsers({
        keyword: "",
        page: currentPage.value,
        size: pageSize.value,
      });
    }

    // 转换用户数据并加载额外信息
    const usersWithStats: UserWithStats[] = await Promise.all(
      response.items.map(async user => {
        try {
          // 并行加载用户统计信息和关注状态
          const [stats, isFollowing] = await Promise.all([
            getUserStats(user.id).catch(() => ({
              postCount: 0,
              commentCount: 0,
              followingCount: 0,
              followerCount: 0,
              likeCount: 0,
              whisperCount: 0,
            })),
            isAuthenticated()
              ? getFollowStatus(user.id).catch(() => false)
              : Promise.resolve(false),
          ]);

          return {
            ...user,
            postCount: stats.postCount,
            followerCount: stats.followerCount,
            followingCount: stats.followingCount,
            isFollowing,
          };
        } catch (error) {
          console.error(`Failed to load data for user ${user.id}:`, error);
          return {
            ...user,
            postCount: 0,
            followerCount: 0,
            followingCount: 0,
            isFollowing: false,
          };
        }
      })
    );

    users.value = usersWithStats;
    total.value = response.total;

    console.log("用户列表加载成功:", users.value);
  } catch (error) {
    console.error("Failed to load users:", error);
    ElMessage.error("加载用户列表失败");

    // 出错时显示空列表
    users.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索用户
const handleSearch = () => {
  currentPage.value = 1;
  loadUsers();
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  loadUsers();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadUsers();
};

// 关注/取消关注
const toggleFollow = async (user: UserWithStats) => {
  if (!isAuthenticated()) {
    ElMessage.warning("请先登录");
    router.push("/login");
    return;
  }

  try {
    if (user.isFollowing) {
      // 取消关注
      await unfollowUser(user.id);
      user.isFollowing = false;
      user.followerCount = Math.max(0, (user.followerCount || 0) - 1);
      ElMessage.success("取消关注成功");
    } else {
      // 关注
      await followUser(user.id);
      user.isFollowing = true;
      user.followerCount = (user.followerCount || 0) + 1;
      ElMessage.success("关注成功");
    }
  } catch (error: any) {
    console.error("关注操作失败:", error);
    ElMessage.error(error.message || "操作失败");
  }
};

// 发送悄悄话
const sendWhisper = (user: UserWithStats) => {
  router.push(`/whisper?to=${user.username}`);
};

// 格式化时间
const formatTime = (time: string) => {
  const date = new Date(time);
  return date.toLocaleDateString();
};

// 组件挂载
onMounted(() => {
  loadUsers();
});
</script>

<style scoped lang="scss">
.user-list-page {
  min-height: 100vh;
  background-color: #f5f5f5;

  .page-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 40px 0;
    text-align: center;

    .header-content {
      max-width: 1200px;
      margin: 0 auto;
      padding: 0 20px;

      h1 {
        margin: 0 0 10px 0;
        font-size: 32px;
        font-weight: 600;
      }

      p {
        margin: 0;
        font-size: 16px;
        opacity: 0.9;
      }
    }
  }

  .page-content {
    max-width: 1200px;
    margin: -20px auto 0;
    padding: 0 20px 40px;

    .search-bar {
      background: white;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      padding: 20px;
      margin-bottom: 24px;

      .el-input {
        max-width: 400px;
      }
    }

    .user-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 24px;
      margin-bottom: 24px;

      .empty-state {
        grid-column: 1 / -1;
        text-align: center;
        padding: 60px 0;
      }

      .user-card {
        background: white;
        border-radius: 12px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        padding: 24px;
        text-align: center;
        transition: transform 0.2s, box-shadow 0.2s;

        &:hover {
          transform: translateY(-4px);
          box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
        }

        .user-avatar {
          margin-bottom: 16px;
        }

        .user-info {
          margin-bottom: 20px;

          .username {
            margin: 0 0 8px 0;
            color: #2c3e50;
            font-size: 18px;
            font-weight: 600;
          }

          .bio {
            margin: 0 0 16px 0;
            color: #606266;
            font-size: 14px;
            line-height: 1.5;
            min-height: 42px; // 保持高度一致
          }

          .user-stats {
            display: flex;
            justify-content: space-around;

            .stat-item {
              display: flex;
              flex-direction: column;
              align-items: center;

              .stat-value {
                font-size: 18px;
                font-weight: 600;
                color: #2c3e50;
              }

              .stat-label {
                font-size: 12px;
                color: #909399;
                margin-top: 4px;
              }
            }
          }
        }

        .user-actions {
          display: flex;
          gap: 8px;
          justify-content: center;
          margin-bottom: 16px;

          .el-button {
            flex: 1;
          }
        }

        .join-time {
          color: #c0c4cc;
          font-size: 12px;
        }
      }
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      background: white;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      padding: 20px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .user-list-page {
    .page-content {
      padding: 0 10px 20px;

      .user-grid {
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: 16px;

        .user-card {
          padding: 20px;
        }
      }
    }
  }
}

@media (max-width: 480px) {
  .user-list-page {
    .page-content {
      .user-grid {
        grid-template-columns: 1fr;
      }
    }
  }
}
</style>
